//
//  XQRealm.swift
//  XQMacRealmDemo
//
//  Created by WXQ on 2019/8/5.
//  Copyright © 2019 WXQ. All rights reserved.
//

import Foundation
import RealmSwift

struct XQRealm {
    
    // 主键不能自增, 是个坑, 个人觉得直接用UUID来做就算了
    
    /// 配置数据库
    /// - Note: 将以下代码写在 AppDelegate 的 didFinishLaunchingWithOptions 方法中
    /// 这个方法主要用于数据模型属性增加或删除时的数据迁移，每次模型属性变化时，将 dbVersion 加 1 即可，Realm 会自行检测新增和需要移除的属性，然后自动更新硬盘上的数据库架构，移除属性的数据将会被删除。
    static func configRealm() {
        /// 如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大
        let dbVersion : UInt64 = 4
        let dbPath = self.realmPath()
        print("dbPath: \(dbPath)")
        
        // 设置默认配置
        let config = Realm.Configuration(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { (migration, oldSchemaVersion) in
            print("migrationBlock: ", migration, oldSchemaVersion)
        }, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil)
        Realm.Configuration.defaultConfiguration = config
        
        // 打开数据库
        Realm.asyncOpen { (realm, error) in
            if let _ = realm {
                print("Realm 服务器配置成功!")
            }else if let error = error {
                print("Realm 数据库配置失败：\(error.localizedDescription)")
            }
        }
        
        
    }
    
    private static var db: Realm?
    
    static func getDB() -> Realm? {
        if let db = self.db {
            return db
        }
        
        let dbPath = self.realmPath()
        /// 传入路径会自动创建数据库
        let defaultRealm = try? Realm(fileURL: URL.init(string: dbPath)!)
        if let defaultRealm = defaultRealm {
            self.db = defaultRealm
            return defaultRealm
        }else {
            print("不存在 defaultRealm")
        }
        return defaultRealm
    }
    
    /// 获取数据库路径
    private static func realmPath() -> String {
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
        
        var path = Bundle.main.bundleIdentifier
        if let _ = path {
            
        }else {
            path = "wxq"
        }
        
        path = path! + ".xqRealm"
        
        // 不会自动创建文件夹, 所以这里要帮 Realm 创建
        try? FileManager.default.createDirectory(atPath: docPath + "/" + path!, withIntermediateDirectories: true, attributes: nil)
        
        path = "/" + path! + "/xq_db.realm"
        let dbPath = docPath.appending(path!)
        return dbPath
    }
    
}


